<?php

namespace App\Http\Controllers\Api\V1\Message;

use App\Http\Controllers\ApiBaseController;
use App\Libs\Commons\MyLogger;
use App\Libs\Commons\MyMessage;
use App\Services\Message\YunpianService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;

class SmsController extends ApiBaseController
{
    public function push(Request $request)
    {
        try {
            $param = $request->all();
            $validator = Validator::make($param, [
                'mobile' => 'required'
            ]);

            if ($validator->fails()) {
                return $this->fail(MyMessage::ERROR, $validator->errors()->first());
            }

            $code = mt_rand(100000, 999999);
            $param = [
                'mobile' => $param['mobile'],
                'text' => '【百姓车联】您的验证码是' . $code . '；请确保本人操作，切勿泄露他人。'
            ];

			Redis::setex('sms:auth:' . $param['mobile'], 300, $code);
			YunpianService::send($param);
			return $this->success();
		} catch (\Throwable $e) {
			MyLogger::error('短信发送失败', ['code' => $e->getCode(), 'msg' => $e->getMessage()]);
			return $this->fail(MyMessage::ERROR, '发送失败');
		}
	}
}
